#!/usr/bin/env groovy

def git_auth = "1fa96864-5699-483b-a920-2af11df61119"
def harbor_auth = "1e0ae5b9-b151-45b9-a94f-bd02d803ff22"
def kubectl_auth = "c26898c2-92c3-4c19-8490-9cf8ff7918ef"

pipeline {
    agent {
        kubernetes {
            yaml '''
apiVersion: v1
kind: Pod
metadata:
  name: jenkins-slave
  namespace: jenkins-prod
spec:
  tolerations:
  - key: "no-pod"
    operator: "Exists"
    effect: "NoSchedule"
  containers:
  - name: docker
    #image: docker:24.0.6
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:24.0.6
    imagePullPolicy: IfNotPresent
    readinessProbe:
      exec:
        command: [sh, -c, "ls -S /var/run/docker.sock"]
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: docker-daemon
    #image: docker:24.0.6-dind
    image: ccr.ccs.tencentyun.com/huanghuanhui/docker:24.0.6-dind
    imagePullPolicy: IfNotPresent
    securityContext:
      privileged: true
    volumeMounts:
    - name: docker-socket
      mountPath: /var/run
  - name: alpine	
    #image: alpine:3.19.0
    image: ccr.ccs.tencentyun.com/huanghuanhui/alpine:3.19.0
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: node-cache
      mountPath: /root/.npm
  - name: node
    #image: node:16.17.0-alpine
    image: ccr.ccs.tencentyun.com/huanghuanhui/node:16.17.0-alpine
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
    volumeMounts:
    - name: node-cache
      mountPath: /root/.npm
  - name: kubectl
    image: kostiscodefresh/kubectl-argo-rollouts:v1.6.0
    imagePullPolicy: IfNotPresent
    command:
    - sleep
    args:
    - 99d
  - name: jnlp
    #image: jenkins/inbound-agent:3206.vb_15dcf73f6a_9-2
    image: ccr.ccs.tencentyun.com/huanghuanhui/jenkins-inbound-agent:3206.vb_15dcf73f6a_9-2
    imagePullPolicy: IfNotPresent
  volumes:
  - name: docker-socket
    emptyDir: {}
  - name: maven-cache
    persistentVolumeClaim:
      claimName: jenkins-prod-slave-maven-cache
  - name: node-cache
    persistentVolumeClaim:
      claimName: jenkins-prod-slave-node-cache
'''
        }
    }


environment {
AppName = "${AppName}"
GitRepo = "${GitRepo}"
GitBranch = "${GitBranch}"
Server = "${Server}"
RepoName = "${RepoName}"
BaseImage = "${BaseImage}"
}

    parameters {
        string(name: 'AppName', defaultValue: 'green-ruoyi-vue', description: '服务名')
        string(name: 'GitRepo', defaultValue: 'https://gitlab.huanghuanhui.com/root/RuoYi-Cloud.git', description: '代码仓库地址')
        string(name: 'GitBranch', defaultValue: 'green', description: '代码版本')
        string(name: 'Server', defaultValue: 'ccr.ccs.tencentyun.com', description: '仓库地址')
        string(name: 'RepoName', defaultValue: 'huanghuanhui/green-ruoyi-vue', description: '仓库名字（仓库自动创建）')
        string(name: 'BaseImage', defaultValue: 'ccr.ccs.tencentyun.com/huanghuanhui/openjdk:8-jre', description: '基础镜像')
    }

    stages {
        stage('拉取代码') {
			steps {
			git branch: "${GitBranch}", credentialsId: "${git_auth}", url: "${GitRepo}"
			}
		}
        
        stage('加载依赖') {
            steps {
              container('alpine') {
                sh """
                  cd ruoyi-ui && cp /root/.npm/node_modules.tar.gz . && tar xf node_modules.tar.gz
                """
                }
            }
        }
        
        stage('代码编译') {
            steps {
              container('node') {
                sh """
                  cd ruoyi-ui && sed -i \'s/localhost/ruoyi-gateway-svc/g\' vue.config.js && npm install --registry=https://registry.npmmirror.com && npm run build:prod
                """
                }
            }
        }

        stage('打包镜像') {
            steps {
              script {env.GIT_COMMIT_MSG = sh (script: 'git rev-parse --short HEAD', returnStdout: true).trim()}
              container('docker') {
sh '''cat > nginx.conf << 'EOF'
worker_processes  auto;

events {
    worker_connections  10240;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }

        location /prod-api/{
            proxy_pass http://ruoyi-gateway-svc:8080/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;
        }

        # 避免actuator暴露
        if ($request_uri ~ "/actuator") {
            return 403;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
EOF

cat > dockerfile << 'EOF'
FROM ccr.ccs.tencentyun.com/huanghuanhui/nginx:1.25.3-alpine

WORKDIR /usr/share/nginx/html

COPY nginx.conf /etc/nginx/nginx.conf

COPY ./ruoyi-ui/dist /usr/share/nginx/html
EOF

docker build -t ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID} .
'''
                }
            }
        }


        stage('推送镜像') {
            steps {
              container('docker') {
                withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
                sh """
                docker login -u ${username} -p '${password}' ${Server}
                docker push ${Server}/${RepoName}:${GitBranch}-${GIT_COMMIT_MSG}-${BUILD_ID}
                """
                   }
                }
            }
        }

        stage('依赖持久化') {
            steps {
              container('alpine') {
                sh """
                  tar zcf node_modules.tar.gz ruoyi-ui/node_modules && mv -f ruoyi-ui/node_modules.tar.gz /root/.npm
                """
                }
            }
        }
    }
}